<template>
    <!-- 维修计划 -->
    <div class="layout-padding">
      <basic-container class="layout-padding-auto layout-padding-view">
        <avue-crud
            v-model='form'
            ref='crud'
            :page='page'
            :data='tableData'
            :table-loading='tableLoading'
            :option='tableOption'
            :before-open="beforeOpen"
            :permission="permissionList"
            @on-load='getList'
            @search-change='searchChange'
            @refresh-change='refreshChange'
            @size-change='sizeChange'
            @current-change='currentChange'
            @row-update='handleUpdate'
            @row-save='handleSave'
            @row-del='rowDel'
            @selection-change='selectionChange'
        >
          <template #menu='scope'>
            <!-- v-if='permissions.om_omrepairplan_execute' -->
            <el-button
                :disabled='scope.row.isExecute==="1"'
                
                @click='handleCarryOut(scope)'
                icon="el-icon-document"
                text
                type="primary">执行
            </el-button>
            </template>
          <template #menu-left>
            <!-- v-if='permissions.om_omrepairplan_del' -->
            <el-button
               
                class='filter-item'
                plain
                type='primary'
                icon='el-icon-delete'
                @click='plDelete'
            >
              批量删除
            </el-button>
            <!-- v-if='permissions.om_omrepairplan_export' -->
            <el-button
               
                class="filter-item"
                plain
                type="primary"
                icon="el-icon-download"
                @click="exportExcel">导出
            </el-button>
          </template>
          <template #deviceName-form='scope'>
            <div class='span-title'>
              <div class='span-input'>
                <el-input
                    :disabled='true'
                    v-model='form.deviceName'
                    placeholder='请选择设备'
                ></el-input>
              </div>
              <div class='span-btn'>
                <el-button
                    :disabled='scope.column.boxType==="edit"'
                    type='primary'
                    plain
                    @click='getDevForm'
                >选择设备
                </el-button
                >
              </div>
            </div>
          </template>
          <template #repairTemplateName-form='scope'>
              <el-select v-model="form.repairTemplateName" style='width: 100%' :disabled='scope.column.boxType==="edit"'>
             <el-option
                 v-for="item in TemplateList"
                 :key="item.id"
                 :label="item.repairTemplateName"
                 :value="item.repairTemplateName"
             />
               </el-select>
          </template>
          <template #areaCode-form>
             <avue-input-tree :disabled='true' filterable type='tree' v-model="form.areaCode" placeholder="请选择内容"
                              :dic="dic"
                              :props='props'>
             </avue-input-tree>
          </template>
          <template #repository-form='scope'>
            <avue-crud :data="data1"
                       :option="option1"
                       @on-load='getData'
                       :selection='false'
            >
              <template #menu='scope'>
                      <el-button
                          @click='handleDownload(scope)'
                          icon="el-icon-download"
                          text
                          type="primary"
                      >下载</el-button>
              </template>
            </avue-crud>
          </template>
          <template #time123-form='scope'>
           <el-tabs v-model="planType" type="border-card">
              <el-tab-pane v-if='form.planType==="0"' label="定期计划" name="0">
               <el-form label-width='160px'>
                 <el-form-item label="计划开始时间" required>
                  <el-col :span="11">
                     <el-date-picker
                         value-format="YYYY-MM-DD"
                         v-model='form.planStartTime'
                         type='date'
                         placeholder='选择起始时间'
                     />
                  </el-col>
                </el-form-item>
                <el-form-item label="周期单位" required>
                  <el-col :span="11">
                    <el-radio-group v-model="form.planCycleType">
                      <el-radio-button label="0">天</el-radio-button>
                      <el-radio-button label="1">月</el-radio-button>
                    </el-radio-group>
                  </el-col>
                </el-form-item>
                <el-form-item label="执行间隔" required>
                  <el-col :span="11">
                    <span>每</span>
                    <el-input-number
                        v-model="form.frequency"
                        controls-position="right"
                        :min="1"
                        :max="maxDays"
                        style="margin: 0 10px"
                    ></el-input-number>
                    <span v-text="form.planCycleType === '0' ? '天' : '月'"></span>
                  </el-col>
                </el-form-item>
                <el-form-item label="执行时间" required>
                  <el-col :span="15">
                   <el-date-picker
                       value-format="YYYY-MM-DD HH:mm:ss"
                       v-model='form.excuteDate'
                       type='datetime'
                       placeholder='选择起始时间'
                   />
                  </el-col>
                </el-form-item>
               </el-form>
              </el-tab-pane>
              <el-tab-pane v-else label="临时计划" name="0">
               <el-form label-width='160px'>
                 <el-form-item label="计划开始时间" required>
                  <el-col :span="11">
                     <el-date-picker
                         value-format="YYYY-MM-DD"
                         v-model='form.planStartTime'
                         type='date'
                         placeholder='选择起始时间'
                     />
                  </el-col>
                </el-form-item>
                <el-form-item label="执行时间" required>
                  <el-col :span="15">
                   <el-date-picker
                       value-format="YYYY-MM-DD HH:mm:ss"
                       v-model='form.excuteDate'
                       type='datetime'
                       placeholder='选择起始时间'
                   />
                  </el-col>
                </el-form-item>
               </el-form>
              </el-tab-pane>
            </el-tabs>
          </template>
        </avue-crud>
      </basic-container>
       <el-dialog
           v-model='dialogVisible'
           title='执行时间'
           width='25%'
           @close='dialogVisible = false'
       >
        <el-form-item label='执行时间'>
            <el-date-picker
                style="width: 80%"
                v-model='executeTime'
                type='datetime'
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder='选择执行时间'
            />
        </el-form-item>
        <template #footer>
          <span class='dialog-footer'>
            <el-button @click='dialogVisible = false'>取消</el-button>
            <el-button type='primary' @click='handleClose'> 确定 </el-button>
          </span>
        </template>
      </el-dialog>
   <DevForm ref='devFormRef' @getDeviceName='getDeviceName'></DevForm>
    </div>
  </template>
  
  <script>
  import {
    fetchList,
    addObj,
    delObj,
    putObj,
    delAllObj,
    getRepositoryList,
    getTemplateList,
    getRegionList,
    execute
  } from '/@/api/maintenance/project'
  import {tableOption} from '/@/const/crud/maintenance/project'
//   import {mapGetters} from 'vuex'
  import {ElLoading} from "element-plus";
  import DevForm from "/@/views/om/eventmanagement/devForm/index.vue";
  
  export default {
    name: 'project',
    data() {
      return {
        parentId: 0,
        infoType: null,
        form: {},
        infoData1: [],
        searchForm: {},
        tableData: [],
        page: {
          total: 0, // 总页数
          currentPage: 1, // 当前页数
          pageSize: 10 // 每页显示多少条
        },
        tableLoading: false,
        tableOption: tableOption,
        selectList: [],
        loading: null,
        value: '',
        planType: '0',
        value1: '',
        cycleType: '1',
        maxDays: 99,
        startTime: '',
        data1: [], // 知识库表格数据
        option1: {
          align: 'center',
          addBtn: false,
          delBtn: false,
          editBtn: false,
          refreshBtn: false,
          columnBtn: false,
          searchShow: false,
          header: false,
          border: true,
          column: [
            {
              label: '知识库名称',
              prop: 'knwlTitle'
            }
          ]
        },
        dialogVisible: false,
        executeTime: '',
        TemplateList: [],
        dic: [],
        props: {
          label: 'subareaCn',
          value: 'subareaCode',
          children:'childrens'
        },
        rowData: {},
        TemplateDic: [],
        TemplateProps: {
          label: 'repairTemplateName',
          value: 'repairTemplateName'
        },
      }
    },
    components: {DevForm},
    watch: {
      'form.repairTemplateName'(newValue, oldValue) {
        if ((oldValue || oldValue === '') && newValue) {
          let o = this.TemplateList.find((item) => {
            return item.repairTemplateName === newValue
          })
          let {id, createBy, createTime, updateBy, updateTime, repairTemplateName, ...objRest} = o
          Object.assign(this.form, objRest)
        }
      },
    },
    computed: {
    //   ...mapGetters(['permissions']),
      permissionList() {
        return {
        //   getBtn: this.validData(this.permissions.om_omrepairplan_get, false),
        //   addBtn: this.validData(this.permissions.om_omrepairplan_add, false),
        //   editBtn: this.validData(this.permissions.om_omrepairplan_edit, false),
        //   delBtn: this.validData(this.permissions.om_omrepairplan_del, false),
        }
      }
    },
    mounted() {
  
    },
    methods: {
      getDevForm() {
        this.$refs.devFormRef.visible = true
      },
      getDeviceName(list) {
        this.form.deviceName = list.deviceName
        this.form.deviceCode = list.unitNo
        this.form.areaCode = list.subareaCode
        this.getTemplateList()
      },
      handleDownload({row: {fileList}}) {
        if (fileList.length === 0) return this.$message.warning('没有下载数据')
        this.downBlobFile(
            '/admin/sys-file/' + fileList[0].bucketName + '/' + fileList[0].fileName,
            {},
            fileList[0].original
        )
      },
      getRegionList() {
        getRegionList().then((res) => {
          this.dic = res.data.records
        })
      },
      getTemplateList() {
        getTemplateList().then((res) => {
          if (res.data.records.length === 0) {
            return this.$message.warning('此设备下无维修模版')
          }
          this.TemplateList = res.data.records
        })
      },
      handleClose() {
        execute(Object.assign(this.rowData, {excuteTime: this.executeTime})).then((res) => {
          this.$message.success('执行成功')
          this.getList(this.page)
        }).catch((res) => {
          this.$message.error('执行失败')
        })
        this.dialogVisible = false
      },
      handleCarryOut({row}) {
        this.rowData = row
        this.dialogVisible = true
        this.executeTime = ''
      },
      getData() {
        getRepositoryList({
          current: 1,
          size: 999,
          knwlType: 0
        }).then((response) => {
          this.data1 = response.data.records
        }).catch(() => {
        })
      },
      disabledDate(time) {
        return time.getTime() < Date.now() - 8.64e7
      },
      beforeOpen(done, type) {
        this.getRegionList()
        if (type === 'add') {
          this.form.planFlag = '0'
          this.form.updateTime123 = '0'
          this.form.planType = '0'
          this.form.planStatus = '0'
          this.form.planCycleType = '0'
          this.form.frequency=1
        }
        done()
      },
      openLoading() {
        this.loading = ElLoading.service({
          lock: true,
          text: 'Loading',
          background: 'rgba(0, 0, 0, 0.7)',
        })
      },
      closeLoading() {
        this.loading.close()
      },
      // 全选按钮
      selectionChange(list) {
        this.selectList = list
      },
      // 获取表格数据
      getList(page, params) {
        this.tableLoading = true
        fetchList(
            Object.assign(
                {
                  current: page.currentPage,
                  size: page.pageSize
                },
                params,
                this.searchForm
            )
        )
            .then((response) => {
              this.tableData = response.data.records
              this.page.total = response.data.total
              this.tableLoading = false
            })
            .catch(() => {
              this.tableLoading = false
            })
      },
      // 删除
      rowDel: function (row, index) {
        this.$confirm('是否确认删除' + row.planName, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
            .then(function () {
              return delObj(row.id)
            })
            .then((data) => {
              this.$message.success('删除成功')
              this.getList(this.page)
            })
            .catch((cancelorerror) => {
            })
      },
      // 修改更新数据
      handleUpdate: function (row, index, done, loading) {
        putObj(row)
            .then((data) => {
              this.$message.success('修改成功')
              done()
              this.getList(this.page)
            })
            .catch(() => {
              loading()
            })
      },
      // 新增数据
      handleSave: function (row, done, loading) {
        row.executeNum = 1
        addObj(row)
            .then((data) => {
              this.$message.success('添加成功')
              done()
              this.getList(this.page)
            })
            .catch(() => {
              loading()
            })
      },
      // 分页大小
      sizeChange(pageSize) {
        this.page.pageSize = pageSize
      },
      // 改变页数
      currentChange(current) {
        this.page.currentPage = current
      },
      // 点击搜索
      searchChange(form, done) {
        this.page.currentPage = 1
        this.getList(this.page, form)
        done()
      },
      // 刷新表格
      refreshChange() {
        this.getList(this.page)
      },
      //批量删除
      plDelete() {
        if (this.selectList.length > 0) {
          this.$confirm('是否确认删除以选择的数据', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
              .then(() => {
                let ids = []
                this.selectList.forEach((data) => {
                  ids.push(data.id)
                })
                this.openLoading()
                return delAllObj(ids).then((res) => {
                  this.closeLoading()
                  this.$message.success('删除成功')
                  this.getList(this.page)
                }).catch(() => {
                  this.closeLoading()
                  this.$message.error('删除失败')
                })
              })
              .then((data) => {
  
              })
              .catch((cancelorerror) => {
              })
        }
      },
      // 导出
      exportExcel() {
        this.downBlobFile('/om/omrepairplan/export', this.searchForm, '维修计划.xlsx')
      },
    }
  }
  </script>
  <style lang='scss' scoped>
  .el-tabs__content {
    .el-form-item {
      margin-top: 20px;
    }
  }
  
  .span-title {
    display: flex;
  
    .span-input {
      flex: 2;
    }
  }
  
  </style>
  